<template>
    <div>
        <div>
            <a-upload name="file"
                          :headers="headers"
                          action="#"
                          @change="handleChange">
                <a-button>
                        <a-icon type="upload" /> Click to Upload
                </a-button>
            </a-upload>
        </div>
    </div>
</template>
<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                headers: {
                    authorization: 'authorization-text',
                    complete: 0
                }
            }
        },
        computed: {
            count() {
                return this.$store.getters.getCount
            }
        },
        methods: {
            handleChange(info) {
                    //将文件列表的总数赋值给vuex的count
                    this.$store.dispatch('increment', info.fileList.length)
                    if (info.file.status !== 'uploading') {
                        const {file: {originFileObj}} = info
                        this.customRequest(originFileObj, info.fileList)
                    }
                    return false
            },
            async customRequest(file, fileList) {
                    const fd = new FormData()
                    fd.append('file', file)
                    const res = await axios({
                        url: 'http://localhost:8082/upload/singleFile', data: fd, method: 'post',
                        onUploadProgress: (progressEvent) => {
                            this.complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                            const task = {name:file.name,complete:this.complete}
                            this.$store.commit('setFileList',task)
                            // eslint-disable-next-line no-console
                            console.log('上传 ' + this.complete +'%')
                        }
                    })
                    for (let i = 0; i < fileList.length; i++) {
                        if (fileList[i].uid === file.uid) {
                            fileList.splice(i, 1)
                            await this.$store.dispatch('increment', fileList.length)
                        }
                    }
                    if (fileList.length === 0) {
                        await this.$store.dispatch('increment', 0)
                    }
                    // eslint-disable-next-line no-console
                    console.log(res.data)
                    if (res.data === 'done') {
                        alert("上传成功")
                    } else if (res.data === "error") {
                        alert("上传失败")
                    }
            },

        }
    }

</script>


<style scoped>
</style>
